<?php

namespace app\api\controller\order;

use app\api\controller\Api;
use app\common\order\model\Suborder as SuborderModel;
use app\common\order\model\SuborderBom;
use app\common\order\model\SuborderUse;

class UseLog extends Api
{

    // 获取订单的消费记录
    public function getList()
    {
        $post = $this->request->post();
        if (empty($post['order_id'])) {
            return error([], 'order_id参数异常');
        }

        $model = new SuborderUse();
        $where = [];
        $where['order_id'] = $post['order_id'];
        $rows = $model->where($where)->order('id desc')->select();
        foreach ($rows as $row) {
            $row->append(['user', 'suborder']);
        }

        return success($rows, '获取数据成功');
    }

    public function create()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        if (empty($post['id'])) {
            return error([], '参数异常');
        }

        if (empty($post['suborder_id'])) {
            return error([], 'suborder_id参数异常');
        }

        $model = new SuborderBom();
        $where = [];
        $where['id'] = $post['id'];
        $row = $model->where($where)->find();
        if (empty($row)) {
            return error([], '数据异常');
        }

        if ($row['suborder_id'] != $post['suborder_id']) {
            return error([], '数据异常');
        }

        // 正则表达式匹配数字 $row['product_unit'] 中 数字
        $pattern = '/\d+/';
        preg_match($pattern, $row['product_unit'], $matches);
        $product_unit = $matches[0];
        $total_amount = $product_unit * $row['amount'];

        // 获取当前的总的使用次数
        $model = new SuborderUse();
        $where = [];
        $where['product_id'] = $row['product_id'];
        $where['order_id'] = $row['order_id'];
        $amount = $model->where($where)->count();

        if ($amount >= $total_amount) {
            return error([], '已经超过最大使用次数');
        }

        $model->startTrans();
        try {

            $data = [
                'order_id' => $row['order_id'],
                'suborder_id' => $row['suborder_id'],
                'product_id' => $row['product_id'],
                'amount' => 1,
                'user_id' => $user['id'],
            ];
            $model->save($data);
            $model->commit();

        } catch (\Exception $e) {
            $model->rollback();
            return error([], '操作失败');
        }

        return success([], '操作成功');
    }
}
